<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Traits\Controllers\AdminTraits;
use App\Transformers\Order\OrderCashTransformer;
use App\Transformers\Order\OrderIndexTransformer;
use App\Transformers\Order\OrderLogTransformer;
use App\Transformers\Order\OrderShowTransformer;
use App\Transformers\Order\OrderTransformer;
use Illuminate\Http\Request;

class OrderController extends Controller
{
    use AdminTraits;

    public $model = Order::class;
    public $transformer = OrderTransformer::class;
    public $indexTransformer = OrderIndexTransformer::class;
    public $showTransformer = OrderShowTransformer::class;
    public $cashTransformer = OrderCashTransformer::class;

    /**
     * 订单首页
     */
    public function index(Request $request)
    {
        //先处理传过来的搜索数据
        $this->formatIndexQuery($request);
        $nickname = $request->input('nickname');
        $phone = $request->input('phone');
        $type_select = $request->input('type');
        $info = $request->input('info');
        $start = $request->input('start') ?? '1111-1-1';
        $end = $request->input('end') ?? '2222-1-1';

        $order_select = $this->getQuery()
            ->pimp() // 自动转换where条件
            ->whereHas('user', function($query) use ($nickname,$phone){
                if ( !empty($nickname) ) {
                    $query->where('nickname', 'like', '%'.$nickname.'%');
                }
                if ( !empty($phone) ) {
                    $query->where('phone', $phone);
                }
            })
            ->whereHas('orderCartInfo', function($query) use ($info){
                if ( !empty($info) ) {
                    $query->where('cart_info', 'like', '%'.$info.'%');
                }
            })
            ->whereBetween('created_at',[$start,$end]);

        $order = $order_select->with('orderCartInfo:order_id,cart_info')
            ->with('user:id,nickname,phone')
            ->paginate($this->getPageLimit());

        // 查询额外信息
        $order_quantity = $order_select->count();  //订单数量
        $order_amount = $order_select->pluck('total_price')->sum(); //订单金额
        $order_quantity_today = $order_select
            ->where('created_at','>',date('Y-m-d 0:0:0',time()))
            ->count(); //今日订单数量
        $order_amount_today = $order_select
            ->where('created_at','>',date('Y-m-d 0:0:0',time()))
            ->pluck('total_price')
            ->sum(); //今日订单金额

        // 查询不同类型的订单数量
        $type = $this->getQuery()
            ->selectRaw('type, count(*) as count')
            ->groupBy('type')
            ->get()->toArray();

        // 查询不同状态的订单数量
        $status = $this->getQuery()
            ->when($type_select, function ($query) use ($type_select){
                $query->where('type',$type_select);
            })
            ->where('is_user_delete',1)
            ->selectRaw('status,count(*) as count')
            ->groupBy('status')
            ->get();

        // 所有订单
        $order_all = $this->getQuery()
            ->when($type_select, function ($query) use ($type_select){
                $query->where('type',$type_select);
            })
            ->count();
        // 用户已删除订单
        $deleted = $this->getQuery()
            ->where('is_user_delete', 0)
            ->when($type_select, function ($query) use ($type_select){
                $query->where('type',$type_select);
            })
            ->count();

        $show = [];
        foreach ($type as $item){
            $show[$item['type']] = $item['count'];
        }
        foreach ($status as $item){
            $show[$item['status']] = $item['count'];
        }

        $show['order_all'] = $order_all;
        $show['deleted'] = $deleted;
        $show['order_quantity'] = $order_quantity;
        $show['order_amount'] = $order_amount;
        $show['order_quantity_today'] = $order_quantity_today;
        $show['order_amount_today'] = $order_amount_today;

        return $this->response->paginator($order, resolve($this->indexTransformer))->meta('show',$show);
    }

    public function show($id)
    {
        $show = $this->getQuery()
            ->with('user:id,nickname')
            ->with('promoter:id,nickname')
            ->with('orderEconomize:order_id,member_price')
            ->findOrFail($id); // findOrFail 查找失败时抛出异常404

        if ($this->policy) {
            $this->authorize('show', $show);
        }

        return $this->response->item($show, resolve($this->showTransformer));
    }

    public function destroy($id, Request $request)
    {
        //explode() 函数把字符串打散为数组。
        //array_filter() 函数用回调函数过滤数组中的元素。删除数组中 array 的所有“空”元素
        $ids = array_filter(explode(',', $id));

        if (empty($ids)) {
            return $this->response->errorBadRequest();
        }
        $this->getQuery()->where('is_user_delete',0)->whereIn($this->getQuery()->getKeyName(), $ids)->delete();

        return $this->response->noContent();
    }

    // 订单操作日志路由
    public function log($id)
    {
        $orderLog = $this->getQuery()->findOrFail($id)->orderLog;

        return $this->response->item($orderLog, resolve(OrderLogTransformer::class));
    }

    // 获取管理员备注路由
    public function remark($id)
    {
        $remark = $this->getQuery()->findOrFail($id)->remark;

        return $this->response->array(['remark' => $remark]);
    }

    // 更新管理员备注路由
    public function update_remark($id, Request $request)
    {
        $remark = $request->input('remark');

        $result = $this->getQuery()->findOrFail($id);

        $result->remark = $remark;

        $result->save();

        return $this->response->noContent();
    }

    // 收银订单路由
    public function cash(Request $request)
    {
        //先处理传过来的搜索数据
        $this->formatIndexQuery($request);

        $data = $this
            ->getQuery()
            ->pimp() //自动转换where条件
            ->with('user:id,nickname')
            ->paginate($this->getPageLimit());

        return $this->response->paginator($data, resolve($this->cashTransformer));
    }

    // 售后退款主页路由
    public function refund(Request $request)
    {
        //先处理传过来的搜索数据
        $this->formatIndexQuery($request);
        $nickname = $request->input('nickname');
        $start = $request->input('start') ?? '1111-1-1';
        $end = $request->input('end') ?? '2222-1-1';

        $order_all = $this->getQuery()->where('refund_status','!=','')->count();

        $refund = $this->getQuery()->where('refund_status','!=','')
            ->selectRaw('refund_status,count(*) as count')
            ->groupBy('refund_status')
            ->get()->toArray();

        $show = [];
        $show['order_all'] = $order_all;

        foreach ($refund as $item){
            $show[$item['refund_status']] = $item['count'];
        }

        $order = $this->getQuery()
            ->pimp()  // 自动转换where条件
            ->whereHas('user', function($query) use ($nickname){
                if ( !empty($nickname) ) {
                    $query->where('nickname', 'like', '%'.$nickname.'%');
                }
            })
            ->whereBetween('created_at',[$start,$end])
            ->where('refund_status','!=','')
            ->with('orderCartInfo:order_id,cart_info')
            ->with('user:id,nickname')
            ->paginate($this->getPageLimit());

        return $this->response->paginator($order, resolve($this->indexTransformer))->meta('show',$show);
    }

    // 退款路由
    public function do_refund(Request $request, $id)
    {
        $order = $this->getQuery()->findOrFail($id);

        if ($request->input('refund_price') > $order->pay_price){
            return $this->response->errorForbidden('退款金额大于支付金额，请修改退款金额');
        }

        $order->refund_price = $request->input('refund_price');
        $order->refund_status = 'refunded';

        $order->save();

        return $this->response->noContent();
    }

    // 拒绝退款路由
    public function refuse_refund(Request $request, $id)
    {
        $order = $this->getQuery()->findOrFail($id);

        $order->refund_reason = $request->input('refund_reason');
        $order->refund_status = 'Refuse_refund';

        $order->save();

        return $this->response->noContent();
    }

    // 订单编辑信息获取路由
    public function edit_log($id)
    {
        $order = $this->getQuery()->findOrFail($id);

        $edit = [];
        $edit['order_number'] = $order->order_number;
        $edit['total_price'] = $order->total_price;
        $edit['total_postage'] = $order->total_postage;
        $edit['pay_postage'] = $order->pay_postage;
        $edit['pay_price'] = $order->pay_price;
        $edit['gain_integral'] = $order->gain_integral;

        return $this->response->array($edit);
    }

    // 订单编辑路由
    public function edit(Request $request, $id)
    {
        $order = $this->getQuery()->findOrFail($id);

        $order->pay_price = $request->input('pay_price');
        $order->gain_integral = $request->input('gain_integral');

        $order->save();

        return $this->response->noContent();
    }

    // 订单发送货
    public function send(Request $request, Order $order)
    {
        $type = $request->input('type');
        switch ($type){
            case 1:
                if ($request->input('send_type') == 'hand'){
                    $order->delivery_name = $request->input('delivery_name');
                    $order->delivery_id = $request->input('delivery_id');
                }

                if ($request->input('send_type') == 'print'){
                    $order->delivery_name = $request->input('delivery_name');
                    $order->express_dump = $request->input('express_dump');
                    $order->sender_name = $request->input('sender_name');
                    $order->sender_phone = $request->input('sender_phone');
                    $order->sender_address = $request->input('sender_address');
                }
                break;

            case 2:
                $order->delivery_name = $request->input('delivery_name');
                $order->delivery_id = $request->input('delivery_id');
                break;

            case 3:
                $order->remark = $request->input('remark');
        }

        $order->status = 'toBeReceived';
        $order->save();

        return $this->response->noContent();
    }

    public function delivery_info($id)
    {
        $delivery_name = $this->getQuery()->findOrFail($id)->delivery_name;
        $delivery_id = $this->getQuery()->findOrFail($id)->delivery_id;

        return $this->response->array([
            'delivery_name' => $delivery_name,
            'delivery_id' => $delivery_id
        ]);
}

    // 订单核销
    public function checked(Order $order)
    {
        if ($order->status == 'toBeWriteOff'){
            $order->is_mer_check = 1;
            $order->status = 'writtenOff';
        }

        $order->save();

        return $this->response->noContent();
    }

    // 订单收货
    public function receive(Order $order)
    {
        $order->status = 'dealDone';

        $order->save();

        return $this->response->noContent();
    }

    // 立即支付
    public function pay_now(Order $order)
    {
        if ($order->status == 'noPaid'){
            $order->status = 'noDelivered';
        }

        $order->save();

        return $this->response->noContent();
    }

    public function rules(Request $request): array
    {
        switch ($request->method()) {
            case 'POST':
                return [
                'user_id' => 'required',
                'cart_id' => 'required',
                'mer_id' => 'required',
                'store_id' => 'required',
                'clerk_id' => 'required',
                'order_number' => 'required|size:20|unique:orders',
                'user_name' => 'required',
                'user_phone' => 'required|regex:/^1[3-9]\d{9}$/',
                'user_address' => 'required',
                'total_num' => 'required|numeric',
                'total_price' => 'required',
                'pay_type' => 'required',
                'delivery_name' => 'required',
                'delivery_code' => 'required',
                'delivery_type' => 'required',
                'delivery_id' => 'required',
                'gain_integral' => 'required|numeric',
                'use_integral' => 'required|numeric',
                'back_integral' => 'required|numeric',
                'unique' => 'required|unique:orders',
                'cost' => 'required',
                'verify_code' => 'required',
            ];
                break;
            case 'PUT':
                return [];
        }
        return [];
    }


    /**
     * 字段
     *
     * @return array
     */
    public function customAttributes(): array
    {
        return [
            'user_id' => '用户id',
            'cart_id' => '购物车id',
            'mer_id' => '商户id',
            'store_id' => '门店id',
            'clerk_id' => '门店店员id',
            'order_number' => '订单号',
            'user_name' => '用户姓名',
            'user_phone' => '用户手机',
            'user_address' => '用户地址',
            'total_num' => '订单商品总数',
            'total_price' => '订单总价(分)',
            'pay_type' => '支付方式',
            'delivery_name' => '快递名称/送货人姓名',
            'delivery_code' => '快递公司编码',
            'delivery_type' => '发货类型',
            'delivery_id' => '快递单号/手机号',
            'gain_integral' => '消费赚取积分',
            'use_integral' => '使用积分',
            'back_integral' => '给用户退了多少积分',
            'unique' => '唯一id(md5加密)类似id',
            'cost' => '成本价(分)',
            'verify_code' => '核销码',
            'remark' => '管理员备注',
        ];
    }

}
